package com.eqdd.yiqidian.ui.companyspace

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.rebuild.OptionBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.ui.IndustryTypeListActivity
import com.eqdd.yiqidian.ui.companyspace.base.BaseSpaceAddActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.model.HttpParams
import org.jetbrains.anko.startActivityForResult

/**
 * Created by jhj on 18-7-10.
 */
class DemandAddActivity : BaseSpaceAddActivity() {
    private val itemList = arrayListOf<ItemBean>()
    private var mSlimAdapterEx: SlimAdapterEx<ItemBean>? = null

    override val title: String
        get() = "发布需求"
    override val url: String
        get() = HttpConfig.BASE_URL + HttpConfig.DEMAND_ADD
    override val isHasImg: Boolean
        get() = false


    override fun uploadParams(): HttpParams {
        val params = HttpParams()
        val id = intent.getIntExtra(Config.ID, -1)
        val bean = slimAdapterEx.data
        val json = Gson().toJson(itemList)
        params.put("productId", id)
        params.put("productName", bean[0].content)
        params.put("GuoBiaoCode", bean[1].content)
        params.put("productType", bean[2].content)
        params.put("productDesc", bean[3].content)
        params.put("indexJson", json)
        return params
    }

    override fun setEditBeans() {
        val list = arrayListOf<ItemBean>()
        val density = resources.displayMetrics.density
        datas.add(SlimEditEnterBean("产品名称", "", 0, "请输入").setNeed(true))
        datas.add(SlimEditEnterBean("国标代码", "", 1, "请输入").setNeed(true))
        datas.add(SlimEditEnterBean("产品类型", "", 2, "请输入").setNeed(true).setDeal(true))
        datas.add(SlimEditEnterBean("产品描述", "", 3, "请输入").setNeed(true))
        datas.add(SlimIndexEnterBean("指标特性：", "", 4, "请选择").setDeal(true).setNeed(true))
        slimAdapterEx.register<SlimIndexEnterBean>(R.layout.list_item_168, SlimInjector { data, injector ->
            injector?.text(R.id.tv_content, data?.title)
                    ?.visible(R.id.tv_add)
                    ?.gone(R.id.iv_arrow)
                    ?.with<RecyclerView>(R.id.recycler_index) {
                        it.layoutManager = LinearLayoutManager(this)
                        it.addItemDecoration(DividerLineItemDecoration(this).setFirstDraw(true).setLeftPadding((density * 20).toInt()).setRightPadding((density * 20).toInt()))
                        mSlimAdapterEx = SlimAdapterEx.create().register<ItemBean>(R.layout.list_item_169, SlimInjector<ItemBean> { data, injector ->
                            injector?.text(R.id.tv_index, data?.indexTypeKey)
                                    ?.text(R.id.tv_index_value, data?.indexTypeValue)
                                    ?.visibility(R.id.layout_image, if (data?.indexImage.isNullOrBlank()) View.GONE else View.VISIBLE)
                                    ?.image(R.id.iv_image, HttpConfig.BASE_URL + data?.indexImage)
                        })?.attachTo(it)?.updateData(list as List<ItemBean>?) as SlimAdapterEx<ItemBean>?
                        ItemClickSupport.addTo(it)
                                .setOnItemLongClickListener { recyclerView, position, v ->
                                    AlertDialog.Builder(this)
                                            .setTitle("提示")
                                            .setMessage("是否删除${"“${itemList[position].indexTypeKey}”?"}")
                                            .setPositiveButton("取消", null)
                                            .setNegativeButton("确定", { _, _ ->
                                                it.removeViewAt(position)
                                                itemList.removeAt(position)
                                                mSlimAdapterEx?.notifyItemRemoved(0)
                                            })
                                            .show()
                                    true
                                }
                    }
        })

    }

    override fun itemClick(p: Int) {
        super.itemClick(p)
        when (p) {
            2 -> startActivityForResult<IndustryTypeListActivity>(2, Config.TYPE to 2, Config.TITLE to "产品类型")
            4 -> {
                val id = intent.getIntExtra(Config.ID, -1)
                startActivityForResult<ProductIndexSelectActivity>(Config.ADD, Config.ID to id)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == Config.ADD && resultCode == Activity.RESULT_OK) {
            val json = data?.getStringExtra("data")
            val bean = Gson().fromJson<ItemBean>(json, object : TypeToken<ItemBean>() {}.type)
            val str = if (bean.indexImage.startsWith("http")) {
                val index = bean.indexImage.indexOf("/", 10, true)
                bean.indexImage.substring(index, bean.indexImage.length)
            } else {
                bean.indexImage
            }
            bean.indexImage = str
            itemList.add(bean)
            mSlimAdapterEx?.updateData(itemList)
            mSlimAdapterEx?.notifyDataSetChanged()
            if (itemList.size > 0) {
                slimAdapterEx.getDataItem(4).content = itemList.size.toString()
            } else {
                slimAdapterEx.getDataItem(4).content = null
            }
        }
        if (requestCode == 2 && resultCode == Activity.RESULT_OK) {
            val bean = data?.getSerializableExtra("data") as? OptionBean
            slimAdapterEx?.getDataItem(2)?.content = bean?.name
            slimAdapterEx?.notifyItemChanged(2)
        }
    }

    class ItemBean {
        var indexTypeKey: String = ""
        var indexTypeValue: String = ""
        var indexImage: String = ""
    }

    class SlimIndexEnterBean(title: String, content: String, position: Int, hintContent: String) : SlimEditBean(title, content, position) {
        var hintContent: String = ""
        var tip: String = ""

        init {
            this.hintContent = hintContent
        }
    }

}